package com.tronsis.library.zxing;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.tronsis.library.R;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.permission.PermissionActivity;
import com.tronsis.library.util.BitmapUtil;
import com.tronsis.library.util.LogUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.zxing.camera.CameraManager;
import com.tronsis.library.zxing.decoding.CaptureActivityHandler;
import com.tronsis.library.zxing.decoding.InactivityTimer;
import com.tronsis.library.zxing.decoding.RGBLuminanceSource;
import com.tronsis.library.zxing.view.ViewfinderView;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;

public class CaptureActivity extends ToolBarBaseActivity implements Callback, View.OnClickListener {

    private Context mContext;
    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;

    private static final int REQUEST_CODE = 100;
    private static final int PARSE_BARCODE_SUC = 300;
    private static final int PARSE_BARCODE_FAIL = 303;
    private ProgressDialog mProgress;

    private static final int ADD_INFO_REQUEST_CODE = 305;
    private static final int FOLLOW_PET_REQUEST_CODE = 307;

    public static final String EXTRA_QR_RESULT = "extra_qr_result";
    private String mIntentType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_capture);
        setTitle(false, "产品扫码");
        mIntentType = getIntent().getType();
        //        setRightTvText("相册");

        //SystemBarTintManager.initWindow(this);
        //setContentView(R.layout.activity_capture);
        //ViewUtil.addTopView(getApplicationContext(), this, R.string.scan_card);
        initData();

        mIBtnBack.setVisibility(View.VISIBLE);
        mIBtnLeft.setVisibility(View.GONE);
        mTvLeft.setVisibility(View.GONE);
    }

    @Override
    protected void onToolbarClicked(int paramId) {
        super.onToolbarClicked(paramId);
        switch (paramId) {
            case RIGHT_TEXT:
                checkPermission(new PermissionActivity.CheckPermListener() {
                    @Override
                    public void superPermission() {
                        Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); //"android.intent.action.GET_CONTENT"
                        innerIntent.setType("image/*");
                        Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");
                        CaptureActivity.this.startActivityForResult(wrapperIntent, REQUEST_CODE);
                    }
                }, R.string.ask_again, Manifest.permission.READ_EXTERNAL_STORAGE);
                break;
        }

    }


    protected void initData() {
        CameraManager.init(getApplication());
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);

        ImageButton mButtonBack = (ImageButton) findViewById(R.id.ibtn_left);
        mButtonBack.setVisibility(View.VISIBLE);
        mButtonBack.setOnClickListener(this);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);

    }


    @Override
    public void onBackPressed() {
        finish();
        super.onBackPressed();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            mProgress.dismiss();
            switch (msg.what) {
                case PARSE_BARCODE_SUC:
                    //Toast.makeText(CaptureActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    isZxing((String) msg.obj);
                    break;
                case PARSE_BARCODE_FAIL:
                    // Toast.makeText(CaptureActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    break;
            }
        }

    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE:
                    //获取选中图片的路径
                    String photoPath = null;
                    Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
                    if (cursor == null) {
                        photoPath = data.getData().getPath();
                    } else {
                        if (cursor.moveToFirst()) {
                            if (StringUtil.isHUAWEI()) {
                                photoPath = getImagePathFromURI(data.getData());
                            } else {
                                try {
                                    photoPath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        cursor.close();
                    }

                    if (!StringUtil.isBlank(photoPath)) {
                        mProgress = new ProgressDialog(CaptureActivity.this);
                        mProgress.setMessage(getString(R.string.scanning));
                        mProgress.setCancelable(false);
                        mProgress.show();
                        final String finalPhotoPath = photoPath;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Result result = scanningImage(finalPhotoPath);
                                if (result != null) {
                                    Message m = mHandler.obtainMessage();
                                    m.what = PARSE_BARCODE_SUC;
                                    m.obj = result.getText();
                                    mHandler.sendMessage(m);
                                } else {
                                    Message m = mHandler.obtainMessage();
                                    m.what = PARSE_BARCODE_FAIL;
                                    m.obj = getString(R.string.scan_fail);
                                    mHandler.sendMessage(m);
                                }
                            }
                        }).start();
                    }
                    break;
            }
        }
    }

    public String getImagePathFromURI(Uri uri) {
        Cursor cursor = mContext.getContentResolver().query(uri, null, null, null, null);
        String path = null;
        if (cursor != null) {
            cursor.moveToFirst();
            String document_id = cursor.getString(0);
            document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
            cursor.close();

            cursor = mContext.getContentResolver()
                             .query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ",
                                     new String[]{document_id}, null);
            if (cursor != null) {
                cursor.moveToFirst();
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                LogUtil.e("path：", path.toString());
                cursor.close();
            }
        }
        return path;
    }

    /**
     * 扫描二维码图片的方法
     *
     * @param path
     * @return
     */
    public Result scanningImage(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码

        Bitmap scanBitmap = BitmapUtil.createBitmap(path);
        try {
            RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
            BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
            QRCodeReader reader = new QRCodeReader();
            return reader.decode(bitmap1, hints);

        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (ChecksumException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }


    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            ToastUtil.showMessage(CaptureActivity.this, getString(R.string.scan_no_camera_permission));
            finish();
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };


    /**
     * 处理扫描结果
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        //        ToastUtil.showMessage(CaptureActivity.this, resultString);
        LogUtil.d("CaptureActivity", "code: " + resultString);

        isZxing(resultString);

        //匹配是否正确的二维码
        //onResultHandler(resultString, barcode);
    }

    private void isZxing(String qrResult) {
        if (TextUtils.isEmpty(qrResult)) {
            //1.无效二维码
            ToastUtil.showMessage(this, getString(R.string.error_qr_code));
        } else {
            if (!StringUtil.isBlank(qrResult)) {
//                ToastUtil.showMessage(this, qrResult);
                //Intent intent = new Intent();
                //intent.putExtra(EXTRA_QR_RESULT, qrResult);
                //setResult(Activity.RESULT_OK, intent);

                Class clazz = null;
                try {
                    if (mIntentType==null){
                        clazz = Class.forName("com.tronsis.distribution.activity.me.QrResultActivity");
                        Intent intent = new Intent(this, clazz);
                        intent.putExtra(EXTRA_QR_RESULT, qrResult);
                        startActivity(intent);
                    }else {
                        if (mIntentType.equals("product")){
                            Intent intent = new Intent();
                            intent.putExtra(EXTRA_QR_RESULT, qrResult);
                            setResult(Activity.RESULT_OK, intent);
                        }
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                CaptureActivity.this.finish();

            } else {
                ToastUtil.showMessage(this, getString(R.string.error_qr_code));
            }
        }

    }


    /**
     * 跳转到上一个页面
     *
     * @param resultString
     * @param bitmap
     */
    private void onResultHandler(final String resultString, Bitmap bitmap) {
        if (TextUtils.isEmpty(resultString)) {
            ToastUtil.showMessage(CaptureActivity.this, "Scan failed!");
            if (handler != null) {
                handler.restartPreviewAndDecode();
            }
            return;
        }
        if (!resultString.startsWith("匹配的url")) {
            ToastUtil.showMessage(CaptureActivity.this, "Invalid QR code");
            if (handler != null) {
                handler.restartPreviewAndDecode();
            }
            return;
        }
    }
}